package com.officegameapp.db.implementation.hibernate;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.officegameapp.db.dao.IPlayerDAO;
import com.officegameapp.db.entities.Player;

public class PlayerDAO implements IPlayerDAO {

	@Override
	public void persist(Player p) {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		session.saveOrUpdate(p);
		session.getTransaction().commit();
	}
	
	@Override
	public void create(Player p) {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		session.save(p);
		session.getTransaction().commit();
	}

	@Override
	public Player read(long id) {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Player player = (Player) session.createCriteria(Player.class)
			.add(Restrictions.eq("id", id)).uniqueResult();
		session.getTransaction().commit();
		return player;
	}

	@Override
	public void delete(Long id) {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Player playerToDelete = (Player) session.createCriteria(Player.class)
			.add(Restrictions.eq("id", id)).uniqueResult();
		session.delete(playerToDelete);
		session.getTransaction().commit();
	}

	@Override
	public List<Player> getPlayers() {
		Session session = HibernateUtil.getSession();
		List<Player> players = (List<Player>) session.createCriteria(Player.class).list();
		return players;
	}

}
